// 检查有效落子位置
export function checkValidMoves(board, player) {
  const opponent = player === 'black' ? 'white' : 'black'
  const validMoves = []
  
  for (let row = 0; row < 8; row++) {
    for (let col = 0; col < 8; col++) {
      if (board[row][col] !== null) continue
      
      // 检查8个方向
      const directions = [
        [-1, -1], [-1, 0], [-1, 1],
        [0, -1],           [0, 1],
        [1, -1],  [1, 0],  [1, 1]
      ]
      
      let foundValid = false
      
      for (const [dx, dy] of directions) {
        let x = col + dx
        let y = row + dy
        let hasOpponent = false
        
        // 检查该方向是否有对手棋子
        while (x >= 0 && x < 8 && y >= 0 && y < 8) {
          if (board[y][x] === null) break
          if (board[y][x] === player) {
            if (hasOpponent) {
              foundValid = true
            }
            break
          }
          if (board[y][x] === opponent) {
            hasOpponent = true
          }
          x += dx
          y += dy
        }
      }
      
      if (foundValid) {
        validMoves.push({ row, col })
      }
    }
  }
  
  return validMoves
}

// 执行落子并返回翻转的棋子
export function makeMove(board, row, col, player) {
  if (board[row][col] !== null) return []
  
  const opponent = player === 'black' ? 'white' : 'black'
  const flipped = []
  
  // 检查8个方向
  const directions = [
    [-1, -1], [-1, 0], [-1, 1],
    [0, -1],           [0, 1],
    [1, -1],  [1, 0],  [1, 1]
  ]
  
  for (const [dx, dy] of directions) {
    let x = col + dx
    let y = row + dy
    let toFlip = []
    let foundPlayer = false
    
    // 检查该方向是否有对手棋子
    while (x >= 0 && x < 8 && y >= 0 && y < 8) {
      if (board[y][x] === null) break
      if (board[y][x] === player) {
        foundPlayer = true
        break
      }
      if (board[y][x] === opponent) {
        toFlip.push({ y, x })
      }
      x += dx
      y += dy
    }
    
    if (foundPlayer && toFlip.length > 0) {
      // 翻转棋子
      toFlip.forEach(({ y, x }) => {
        board[y][x] = player
        flipped.push({ y, x })
      })
    }
  }
  
  if (flipped.length > 0) {
    board[row][col] = player
  }
  
  return flipped
}

// 检查游戏结果
export function checkWinner(board) {
  let black = 0
  let white = 0
  
  for (let row = 0; row < 8; row++) {
    for (let col = 0; col < 8; col++) {
      if (board[row][col] === 'black') black++
      if (board[row][col] === 'white') white++
    }
  }
  
  if (black > white) {
    return { winner: 'black', black, white }
  } else if (white > black) {
    return { winner: 'white', black, white }
  } else {
    return { winner: 'draw', black, white }
  }
}